package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;

import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.market.Player;

public class MarketBuySync 
{
	// comprar changes
	private static final String MARKET_BUY_GET = InitSync.BASE_URL+"/mercado.php";
	
	// el service
	private SupermanagerService service;
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// jornada passada de loginSyn pq no es a les pagines de market
	private Integer jornada = null;
	
	// status de retorn
	public int status = -1;
	
	public ArrayList<Player> players;
	
	public MarketBuySync(SupermanagerService service, DefaultHttpClient client, Integer jornada)
	{
		this.service = service;
		this.client = client;
		this.jornada = jornada;
	}
	
	// sync the three market players posistions
	public void sync(String idequ, String position)
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();

			if( !online )
				throw new ConnectivityException();
			
			// parse players
			parse(idequ, position);
			
			// persist players
			persistPlayers();

			// parsejat ok
	        status = Supermanager.MARKET_BUY_OK;
	        Log.d(Supermanager.TAG, "MarketBuySync status: MARKET_BUY_OK - "+status);
	        return;
		}
		catch(ConnectivityException ce){
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
	        Log.d(Supermanager.TAG, "MarketBuySync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		}
		catch(Exception e){
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
	        Log.d(Supermanager.TAG, "MarketBuySync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
	}
	
	private void parse(String idequ, String position) throws Exception
	{
		HttpGet httpGet = new HttpGet(MARKET_BUY_GET+"?id_equ="+idequ+"&posicion="+position);
		HttpResponse response = client.execute(httpGet);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String buyMarketPage = os.toString(HTTP.ISO_8859_1);

		//MarketBuyParser parser = MarketBuyParserProvider.getImpl(Package.getPackage("cat.joronya.supermanager.service.htmlcleanerImpl"));
		MarketBuyParser parser = MarketBuyParserProvider.getImpl(Package.getPackage("cat.joronya.supermanager.service.substrImpl"));
		Log.d(Supermanager.TAG, "Start parsing market buy page...");
		long elapsedTime = parser.parse(buyMarketPage, jornada);
		Log.d(Supermanager.TAG, "Stop parsing market buy page! Elapsed time: "+elapsedTime/1000);

		players = parser.getPlayers();
		status = Supermanager.MARKET_BUY_OK;
		Log.d(Supermanager.TAG, "MarketBuySync status: MARKET_BUY_OK - "+status);
	}
	
	/**
	 * Guardar les dades trobades a DB, update dels players q poden.
	 */
    protected void persistPlayers()
    {
    	// no players parsed...
    	if( players == null )
    	{
    		Log.d(Supermanager.TAG,"MarketBuySync persistPlayers parserd 0 players, nothing to update");
    		return;
    	}
    	
    	// update per posar el showInBuy a false de tots inicialment
    	ContentValues resetShownValues = new ContentValues(); 
    	resetShownValues.put(Supermanager.Market.SHOWN_IN_BUY, 0);
    	
    	// update nomes
		if( service.getContentResolver().update(Supermanager.Market.CONTENT_URI, 
				resetShownValues, 
				Supermanager.Market.DAY+" = ? ", 
				new String[]{jornada.toString()}) == 0 )
		{
			return;
		}
		
    	Log.d(Supermanager.TAG,"MarketBuySync persistPlayers parserd "+players.size()+" players, going to update");
    	for(Player p: this.players)
    	{
    		// update el player al market
    		if( !updateBuyPlayer(p) )
    			Log.d(Supermanager.TAG,"MarketBuySync persistPlayers error updating players: "+p.getId()+" on day: "+p.getDay());
    	}
    }
    
	/**
     * Update buy market data, when called from team detail on buy player.
     * @param uri
     * @param p
     * @return
     */
    private boolean updateBuyPlayer(Player p)
    {
    	Log.d(Supermanager.TAG,"MarketBuySync.updateBuyPlayer player id: "+p.getId());
    	
    	// updatem dades del player
		ContentValues values = new ContentValues();
		values.put(Supermanager.Market.SHOWN_IN_BUY, 1);
		if( p.getColorInBuy() != null )
			values.put(Supermanager.Market.COLOR_IN_BUY, p.getColorInBuy());
		else
			values.put(Supermanager.Market.COLOR_IN_BUY, "Black");
		
		// hack per evitar borrar la taula de market per treure el unique sobre idjug,
		// si no tenim idjug, posem el codi del jugador. No s'ha d'emprar.
		if( p.getId() == null )
			values.put(Supermanager.Market.ID_PLAYER, "FAKE"+p.getCodi());
		else
			values.put(Supermanager.Market.ID_PLAYER, p.getId());
		
		// altres valors utils quan parsejem el market
		values.put(Supermanager.Market.STATUS, p.getStatus());
		values.put(Supermanager.Market.NACIONALITY, p.getNacionality());
		values.put(Supermanager.Market.INFO, p.getInfo());
		
		// update nomes, pero amb el codi, pq el id_jug els q no son comprables no
		// el tenim, no esta al html parsejat
		if( service.getContentResolver().update(Supermanager.Market.CONTENT_URI, 
				values, 
				Supermanager.Market.CODI_PLAYER+" = ? AND "+
				Supermanager.Market.DAY+" = ? ", 
				new String[]{p.getCodi(),p.getDay().toString()}) == 0 )
		{
			return false;
		}
		
		return true;
    }
}
